// 2025/3/8
// https://leetcode.cn/problems/merge-k-sorted-lists/?envType=study-plan-v2&envId=top-100-liked
// 合并k个升序链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    public:
        struct Compare{
            bool operator()(const ListNode* n1, const ListNode* n2){
                return n1->val > n2->val;
            }
        };
    
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            int n = lists.size();
            Compare com;
            ListNode head, *phead = &head;
            priority_queue<ListNode*, vector<ListNode*>, Compare> pq(com);
            for(auto& e : lists)
            {
                if(e) pq.emplace(e);
            }
            while(!pq.empty())
            {
                phead->next = pq.top();
                pq.pop();
                phead = phead->next;
                if(phead && phead->next)
                    pq.emplace(phead->next);
            }
            return head.next;
        }
    };